import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import shortcutsApi from '/@/api/shortcuts';

export interface Shortcut {
  ID: string;
  UserId?: string;
  MenuId?: string;
  MenuName: string;
  MenuIcon: string;
  MenuUrl: string;
  SortOrder?: number;
  IconType?: 'element' | 'custom';
}

export const useShortcutsStore = defineStore('shortcuts', () => {
  // 状态
  const shortcuts = ref<Shortcut[]>([]);
  const loading = ref(false);
  const lastFetchTime = ref<number>(0);
  const cacheExpiry = 5 * 60 * 1000; // 5分钟缓存
  const refreshTimer = ref<ReturnType<typeof setTimeout> | null>(null);
  const isRefreshing = ref<boolean>(false);

  // 计算属性
  const shortcutsMap = computed(() => {
    const map = new Map<string, Shortcut>();
    shortcuts.value.forEach(shortcut => {
      if (shortcut.MenuId) {
        map.set(shortcut.MenuId, shortcut);
      }
      if (shortcut.MenuUrl) {
        map.set(shortcut.MenuUrl, shortcut);
      }
    });
    return map;
  });

  // 检查菜单是否在常用功能中
  const isInShortcuts = (menuId: string, menuUrl?: string): boolean => {
    return shortcutsMap.value.has(menuId) || (!!menuUrl && shortcutsMap.value.has(menuUrl));
  };

  // 获取常用功能
  const getShortcut = (menuId: string, menuUrl?: string): Shortcut | undefined => {
    return shortcutsMap.value.get(menuId) || (menuUrl ? shortcutsMap.value.get(menuUrl) : undefined);
  };

  // 加载常用功能列表
  const loadShortcuts = async (force = false) => {
    const now = Date.now();

    // 如果数据还在缓存期内且不是强制刷新，直接返回
    if (!force && shortcuts.value.length > 0 && (now - lastFetchTime.value) < cacheExpiry) {
      return shortcuts.value;
    }

    // 如果正在加载中，直接返回当前数据
    if (loading.value) {
      return shortcuts.value;
    }

    try {
      loading.value = true;
      const response = await shortcutsApi().getList({
        Page: 1,
        Limit: 50,
      });

      if (response.Data) {
        shortcuts.value = response.Data.map((item: any) => {
          const iconType = item.MenuIcon?.startsWith('ele-') ? 'element' : 'custom';
          return {
            ...item,
            IconType: iconType,
            MenuIcon: item.MenuIcon,
          };
        });
        lastFetchTime.value = now;
      }

      return shortcuts.value;
    } catch (error) {
      console.warn('加载常用功能失败:', error);
      return shortcuts.value;
    } finally {
      loading.value = false;
    }
  };

  // 添加常用功能
  const addShortcut = async (shortcutData: any) => {
    try {
      const response = await shortcutsApi().add(shortcutData);
      const newShortcut: Shortcut = {
        ID: response.Data?.ID || Date.now().toString(),
        MenuId: shortcutData.Entity.MenuId,
        MenuName: shortcutData.Entity.MenuName,
        MenuIcon: shortcutData.Entity.MenuIcon,
        MenuUrl: shortcutData.Entity.MenuUrl,
        IconType: shortcutData.Entity.MenuIcon?.startsWith('ele-') ? 'element' : 'custom',
        SortOrder: shortcuts.value.length + 1,
      };
      shortcuts.value.push(newShortcut);
      // 不触发全局刷新，只更新本地状态
      return newShortcut;
    } catch (error) {
      throw error;
    }
  };

  // 编辑常用功能
  const editShortcut = async (shortcutData: any) => {
    try {
      await shortcutsApi().edit(shortcutData);
      const index = shortcuts.value.findIndex(s => s.ID === shortcutData.Entity.ID);
      if (index > -1) {
        shortcuts.value[index] = {
          ...shortcuts.value[index],
          ...shortcutData.Entity,
          MenuIcon: shortcutData.Entity.MenuIcon,
          IconType: shortcutData.Entity.MenuIcon?.startsWith('ele-') ? 'element' : 'custom',
        };
      }
      // 不触发全局刷新，只更新本地状态
    } catch (error) {
      throw error;
    }
  };

  // 删除常用功能
  const deleteShortcut = async (id: string) => {
    try {
      await shortcutsApi().delete([id]);
      const index = shortcuts.value.findIndex(s => s.ID === id);
      if (index > -1) {
        shortcuts.value.splice(index, 1);
      }
      // 不触发全局刷新，只更新本地状态
    } catch (error) {
      throw error;
    }
  };

  // 防抖刷新数据
  const debouncedRefresh = (delay = 300) => {
    if (refreshTimer.value) {
      clearTimeout(refreshTimer.value);
    }

    if (isRefreshing.value) {
      return Promise.resolve(shortcuts.value);
    }

    return new Promise<Shortcut[]>((resolve) => {
      refreshTimer.value = setTimeout(async () => {
        try {
          isRefreshing.value = true;
          const result = await loadShortcuts(true);
          resolve(result);
        } finally {
          isRefreshing.value = false;
        }
      }, delay);
    });
  };

  // 刷新数据
  const refreshShortcuts = () => {
    return debouncedRefresh(100); // 100ms防抖
  };

  // 清空数据
  const clearShortcuts = () => {
    shortcuts.value = [];
    lastFetchTime.value = 0;
  };

  return {
    // 状态
    shortcuts,
    loading,

    // 计算属性
    shortcutsMap,

    // 方法
    loadShortcuts,
    addShortcut,
    editShortcut,
    deleteShortcut,
    refreshShortcuts,
    clearShortcuts,
    isInShortcuts,
    getShortcut,
  };
}); 